package com.ysd.service.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ysd.service.config.WeChatConfig;
import com.ysd.service.dto.UserDto;
import com.ysd.service.entity.User;
import com.ysd.service.entity.Version;
import com.ysd.service.service.ClockService;
import com.ysd.service.service.UserService;
import com.ysd.service.service.VersionService;
import com.ysd.service.util.*;
import com.ysd.service.vo.WxLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private WeChatConfig weChatConfig;
    @Autowired
    private WeChatUtil weChatUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private ClockService clockService;
    @Autowired
    private VersionService versionService;

    /**
     * 小程序登录授权
     */
    @RequestMapping(value = "/wx/login", method = RequestMethod.POST)
    public Result<WxLoginVo> wxLogin(@RequestBody String jsonString){
        log.info("/wx/login.param = " + jsonString);

        JSONObject paramJson = JSONObject.parseObject(jsonString);
        String jsCode = paramJson.getString("code");
        String result = weChatUtil.getAccessTokenAndOpenId(weChatConfig.getAppId(), weChatConfig.getAppSecret(), jsCode);
        if (StringUtils.isBlank(result) || "".equals(result)) {
            log.info("wxLogin getSessionKey,-> 获取sesstionkey失败");
            return Result.buildResult(Result.Status.WX_LOGIN_FAIL,"获取sesstionkey失败");
        }
        // 封装dto
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(StringUtils.isBlank(jsonObject.getString("openid"))){
            log.info("wxLogin getSessionKey,-> 获取openid为空");
            return Result.buildResult(Result.Status.WX_LOGIN_FAIL,"获取openid为空");
        }
        WxLoginVo dto = new WxLoginVo();
        dto.setOpenid(jsonObject.getString("openid"));
        dto.setUnionid(jsonObject.getString("unionid"));
        dto.setAccessToken(jsonObject.getString("access_token"));

        // 查询openid是否存在，不存在则添加用户
        Boolean existOpenId = userService.isExistOpenId(jsonObject.getString("openid"));
        if(!existOpenId){
            // 添加用户
            User user = new User();
            user.setNickName("用户" + RandomUsernameUtil.generateRandomString(6));
            user.setOpenId(jsonObject.getString("openid"));
            user.setUnionId(jsonObject.getString("unionid"));
            user.setAvatar("avatar1.jpg");
            user.setPhone(null);
            user.setDelFlag(0);
            userService.addUser(user);
        }

        return Result.buildResult(Result.Status.OK,"OK",dto);
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/wx/logout", method = RequestMethod.POST)
    public Result wxLogOut(@RequestBody String openid){
        log.info("/wx/logout.param = " + openid);

        openid = JSONObject.parseObject(openid).getString("openid");

        // 删除本地用户
        userService.delUser(openid);

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 查询用户详情
     */
    @RequestMapping(value = "/user/detail", method = RequestMethod.POST)
    public Result<User> getUserDetailByOpenid(@RequestBody String openid){
        log.info("/user/detail.param = " + openid);
        return Result.buildResult(Result.Status.OK,"OK", userService.getUserDetailByOpenid(openid));
    }

    /**
     * 修改用户头像
     */
    @RequestMapping(value = "/user/editAvatar", method = RequestMethod.PUT)
    public Result editUserAvatar(@RequestBody UserDto dto){
        log.info("/user/editAvatar.param = " + dto);
        userService.editUserAvatar(dto);
        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 修改用户昵称
     */
    @RequestMapping(value = "/user/editNickName", method = RequestMethod.PUT)
    public Result editUserNickName(@RequestBody UserDto dto){
        log.info("/user/editNickName.param = " + dto);
        userService.editUserAvatar(dto);
        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 查询最新版本信息
     */
    @RequestMapping(value = "/version/detail", method = RequestMethod.GET)
    public Result<Version> getUserDetailByOpenid(){
        log.info("/version/detail ========== ");
        return Result.buildResult(Result.Status.OK,"OK", versionService.getCurrentVersion());
    }

    /**
     * 小程序用户信息授权
     */
    @RequestMapping(value = "/wx/userProfile", method = RequestMethod.POST)
    public Result wxUserProfile(@RequestBody String jsonString){
        log.info("/wx/userProfile.param = " + jsonString);

        JSONObject paramJson = JSONObject.parseObject(jsonString);
        String userInfoStr = paramJson.getString("userInfo");
        String openid = paramJson.getString("openid");
        JSONObject userInfo = JSONObject.parseObject(userInfoStr);

        // 增加用户信息数据
        User user = new User();
        user.setOpenId(openid);
        user.setNickName(userInfo.getString("nickName"));
        user.setAvatar(userInfo.getString("avatarUrl"));
        userService.editorUser(user);

        return Result.buildResult(Result.Status.OK,"OK");
    }


}
